class Translate:
    def translate(self,value):
        from requests import post
        url = 'https://fanyi.youdao.com/translate'
        data = {
            'i': value,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'lts': '1662381146940',
            'bv': '01e27702dbb21a6d2b97645ec075ab88',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTlME'
        }
        res = post(url, data=data).json()['translateResult'][0][0]['tgt'].upper()
        if ' ' in res:
            res = res.replace(' ', '_')
        return res

    def Create_tbale(self):
        file = open('./api_list.txt', mode='r', encoding='utf-8')
        content = eval(str(eval(file.read()).keys())[10:-1])
        file.close()
        l = []
        for value in content:
            name = Translate().translate(value)
            CREATE_TABLE = f"""
                    create table {name}(
                    content varchar(255)
                    );
                    """
            l.append(CREATE_TABLE)
        return l

class Initialize:
    def __init__(self):
        def mysql_config():  # 获取数据库连接的基本信息
            try:
                file = open('./config.txt', mode='r', encoding='utf-8')
                content = eval(file.read())
                file.close()
                return content
            except Exception as err:
                file.close()
                return "数据库配置文件错误，请检查config.txt文件"

        import pymysql
        # mysql 拥有创建数据库的权限
        host = mysql_config()['host']
        user = mysql_config()['user']
        password = mysql_config()['password']
        port = int(mysql_config()['port'])
        self.authority = mysql_config()['database_authority']
        try:
            self.con = pymysql.connect(host=host, user=user, passwd=password, port=port)
            self.cur = self.con.cursor()
        except Exception as err:
            return "数据库连接失败，请检查config.txt文件,错误信息: ", err


        self.translate = Translate().Create_tbale()



    def file(self):
        try:
            self.file = open('./api_list.txt', mode='r', encoding='utf-8')
            self.content = eval(self.file.read())
            self.file.close()
            return self.content
        except Exception as err:
            return "api设置错误，错误信息: ", err

    def mysql(self):  # 初始化数据库配置信息,创建数据库以及数据表
        def database_not_authority():
            # mysql没有创建数据库的权限
            try:  # 排除出创建数据库自带的库
                show_database = self.cur.execute("show databases;")
                self.databases = []
                err_database = ["sys", "information_schema", "mysql", "performance_schema"]
                for database in self.cur.fetchall():
                    if database[0] in err_database:
                        continue
                    self.databases.append(database[0])
            except Exception as err:
                return "选择数据库时错误,错误信息: ", err
            try:  # 选择任意一个数据库开始创建表
                database = self.databases[0]
                use_database = self.cur.execute(f"use {database};")
                from os import path
                if not path.exists('database.txt'):
                    file = open('database.txt', 'w')
                    file.close()
                file = open('database.txt', 'w')
                result = {}
                result['database'] = database
                file.write(str(result))
                file.close()
            except Exception as err:
                return "选择数据库时错误,错误信息为: ", err  # 选择数据库
            try:
                for create_table in self.translate: # 创建表,依据api_list.txt文件中的api数量创建翻译好多相应的表
                    self.new_table = self.cur.execute(create_table)
            except Exception as err:
                return 'not_authority(create table): ',err # 如果报错，以上顺序都没有问题，那么就是数据表已经存在，过滤无视掉即可
            finally:
                self.cur.close()  # 关闭数据库
                self.con.close()

        def database_authority():
            # mysql有创建数据库的权限
            try:
                self.new_database = self.cur.execute("create database API")
            except Exception as err:
                pass  # 已经连接好了数据库，如果有报错信息那么一定就是数据库已经存在，过滤掉该信息就好
            finally:
                try:
                    self.use_datebase = self.cur.execute("use API;")
                except Exception as err:
                    return  'authority(create datebase): ',err  # 如果选择数据库失败，过滤掉就好
                try:
                    for create_table in self.translate:  # 创建表,依据api_list.txt文件中的api数量创建翻译好所对相应的表
                        self.new_table = self.cur.execute(create_table)
                except Exception as err:
                    return  'authority(create table): ',err # 如果报错，以上顺序都没有问题，那么就是数据表已经存在，过滤无视掉即可
                finally:
                    self.cur.close()  # 关闭数据库
                    self.con.close()

        def if_authority():
            if self.authority == '':
                return database_authority()
            else:
                return database_not_authority()


        return if_authority()





def play():
    ini = Initialize()
    mysql = ini.mysql() # 初始化mysql配置文件
    file = ini.file()   # 初始化api配置文件
    con = ini.con   # 连接数据库
    cur = ini.cur   # 数据库语句
    tra = Translate()
    translate = tra.translate
    creat_table = tra.Create_tbale()
    return mysql,file,con,cur,translate,creat_table

# play()

ini = Initialize()
mysql = ini.mysql()  # 初始化mysql配置文件